'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 抽奖
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var moment = require('moment');
var constantUtil = require('../../../util/constantUtil');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var roleModel = require('../../../models/roleModel');
var dataApi = require('../../../libs/dataApi');
var PlayerManager = require('../../../libs/playerManager');
var rewardService = require('../../../services/rewardService');
var roleService = require('../../../services/roleService');
var genRewardService = require('../../../services/genRewardService');
var randomUtil = require('../../../util/randomUtil');
var luckyConf = require('../../../config/luckyConf');
var turntableConf = require('../../../config/turntableConf.js');
var dealRewardService = require('../../../services/dealRewardService');
var taskService = require('../../../services/taskService');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 新手引导转盘领取奖励
 */
Handler.prototype.guideReceive = function (msg, session, next) {
    var role_id = session.uid;
    var position_id = msg.position_id;

    var reward_list = [];
    // jshint maxstatements:100
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'lucky', 'role', 'soldier', 'build', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var lucky_model = player_manager.lucky;

                // 是否领取过新手材料
                if (!!lucky_model.getGuideState()) {
                    return next(null, {
                        code: Code.TURNTABLE_NOT_REQUIRE
                    });
                }

                var reward_item = dataApi.guide_turntable.findById(position_id) || {};
                reward_list.push(reward_item);
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ACT_TURN_TABLE, operationType.OPR_ACT_TURN_TABLE_OPEN);

                //记录新手奖励发放状态
                lucky_model.setGuideState();
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};

/**
 * 转盘列表
 */
Handler.prototype.turntaList = function (msg, session, next) {
    var role_id = session.uid;
    var now_reward_list = [];
    var free_reset_num = 0;
    var multiple = 1;
    var player_manager = new PlayerManager(role_id);

    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'lucky', 'role', 'build', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var lucky_model = player_manager.lucky;

                // 免费重置次数
                free_reset_num = lucky_model.getTurntableNum();

                // 奖励列表
                now_reward_list = lucky_model.getNowRewardList();
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    now_reward_list: now_reward_list,
                    free_reset_num: free_reset_num
                }
            });
        }
    );
};

/**
 * 领取奖励
 */
Handler.prototype.receive = function (msg, session, next) {
    var role_id = session.uid;
    var position_id = 0;
    var reward_list = [];
    var all_reward_position = [];

    var turntable_open_time = constantUtil.value('turntable_open_time');
    var turntable_finish_time = constantUtil.value('turntable_finish_time');
    var now_tm = moment().unix();
    if (now_tm < turntable_open_time || turntable_finish_time < now_tm) {
        return next(null, {
            code: Code.ACTIVITY_OUT_OF_DATE
        });
    }

    // jshint maxstatements:100
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'lucky', 'role', 'build', 'soldier', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var lucky_model = player_manager.lucky;

                var num = lucky_model.getNum();

                // 转盘是否开启
                var open_time = constantUtil.value('turntable_open_time');
                var end_time = constantUtil.value('turntable_finish_time');
                var now_time = moment().unix();
                if (now_time < open_time || end_time < now_time) {
                    return next(null, {
                        code: Code.TURNTABLE_OPEN_TIME_NOT
                    });
                }
                // 是否还有可抽取奖励
                if (!lucky_model.isStart()) {
                    return next(null, {
                        code: Code.TURNTABLE_NOT_REWARD
                    });
                }

                var all_reward_position1 = lucky_model.receive_turntable_list;
                _.some(all_reward_position1, function (item) {
                    all_reward_position.push(item.new_id);
                });

                var reward_type = turntableConf.getConsume(num).reward;
                var data2 = reward_type.split(',');
                var reward_list_id = [];
                _.each(data2, function (value) {
                    reward_list_id.push(+value);
                });

                // 取当前可随机的奖励
                var open_reward_list = [];
                _.each(reward_list_id, function (value) {
                    if (_.indexOf(all_reward_position, value) !== -1) {
                        open_reward_list.push(value);
                    }
                });

                // 随机奖励
                var random_num = _.random(0, open_reward_list.length - 1);
                var reward_item_position = open_reward_list[random_num];
                position_id = reward_item_position;

                // 扣除钻石
                var sub_diamond = turntableConf.getConsume(num).cost_point;
                if (!!sub_diamond) {
                    if (!roleService.subDiamond(player_manager, moduleType.MDL_ACT_TURN_TABLE, operationType.OPR_ACT_TURN_TABLE_OPEN, sub_diamond)) {
                        return next(null, {
                            code: Code.USER_DIAMOND_NOT_ENOUGH
                        });
                    }
                }

                // 移除
                lucky_model.removeId(reward_item_position);

                // 标记领取状态
                lucky_model.setRewardList(reward_item_position);
                var reward_item = lucky_model.getRewardList(reward_item_position);

                // 扣除次数
                if (!lucky_model.addNum()) {
                    return next(null, {
                        code: Code.TURNTABLE_NOT_REWARD
                    });
                }

                // 发放奖励
                reward_list.push(reward_item);
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ACT_TURN_TABLE, operationType.OPR_ACT_TURN_TABLE_OPEN);

                // 转盘次数统计
                taskService.addCompleteLuckyNum(player_manager);
                cb();
            },
            function (cb) {
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list,
                    position_id: position_id
                }
            });
        }
    );
};

// /**
//  * 转盘重置
//  */
// Handler.prototype.turntableReset = function (msg, session, next) {
//     var role_id = session.uid;
//     var reward_list = [];
//     var player_manager = new PlayerManager(role_id);
// 
//     async.waterfall(
//         [
// 
//             function (cb) {
//                 player_manager.refreshData(cb);
//             },
//             function (cb) {
//                 player_manager.getModel(
//                     ['bag', 'lucky', 'role', 'build', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
//                     cb
//                 );
//             },
//             function (cb) {
//                 var role_model = player_manager.role;
//                 var lucky_model = player_manager.lucky;
// 
//                 // 是否有免费次数
//                 if (!lucky_model.getTurntableNum()) {
//                     if (!roleService.subDiamond(player_manager, moduleType.MDL_ACT_TURN_TABLE, operationType.OPR_ACT_TURN_TABLE_REFRESH, constantUtil.value('turntable_reset_cost'))) {
//                         return next(null, {
//                             code: Code.USER_DIAMOND_NOT_ENOUGH
//                         });
//                     }
//                 }
// 
//                 // 扣除次数
//                 lucky_model.subTurntableNum();
// 
//                 // 重置
//                 lucky_model.reset();
// 
//                 lucky_model.setNum();
//                 reward_list = lucky_model.getNowRewardList();
//                 player_manager.save(cb);
//             }
//         ],
//         function (err) {
//             if (!!err) {
//                 console.error(err);
//                 return next(null, {
//                     code: Code.FAIL
//                 });
//             }
//             return next(null, {
//                 code: Code.OK,
//                 result: {
//                     reward_list: reward_list
//                 }
//             });
//         }
//     );
// };
